<template>
  <view class="profile-container">
    
    <!-- 头像部分 -->
    <view class="avatar-section">
      <!-- #ifdef MP-WEIXIN -->
      <!-- 微信小程序环境下，使用button包装头像 -->
      <button class="avatar-btn" open-type="chooseAvatar" @chooseavatar="onChooseWxAvatar">
        <view class="avatar-container">
          <image class="avatar" :src="avatarUrl" mode="aspectFill" />
          <view class="avatar-edit-icon">
            <text class="iconfont icon-edit">✏️</text>
          </view>
        </view>
      </button>
      <!-- #endif -->
      
      <!-- #ifndef MP-WEIXIN -->
      <!-- 非微信小程序环境下的普通头像区域 -->
      <view class="avatar-container" @tap="showAvatarActionSheet">
        <image class="avatar" :src="avatarUrl" mode="aspectFill" />
        <view class="avatar-edit-icon">
          <text class="iconfont icon-edit">✏️</text>
        </view>
      </view>
      <!-- #endif -->
      
      <text class="avatar-tip">点击头像更换</text>
    </view>
    
    <!-- 表单部分 -->
    <view class="form-section">
      <view class="form-item">
        <text class="label">昵称</text>
        <input
          class="input"
          type="nickname"
          v-model="nickname"
          placeholder="请输入昵称"
          @blur="onNicknameBlur"
        />
      </view>
      
      <view class="form-item">
        <text class="label">手机号</text>
        <input
          class="input"
          type="number"
          v-model="phone"
          placeholder="请输入手机号"
          maxlength="11"
        />
      </view>
      
      <view class="form-item">
        <text class="label">邮箱</text>
        <input
          class="input"
          type="text"
          v-model="email"
          placeholder="请输入邮箱地址"
        />
      </view>
      
      <view class="form-item">
        <text class="label">性别</text>
        <view class="radio-group">
          <view class="radio-item" @tap="gender = 0">
            <view class="radio-circle" :class="{ 'radio-active': gender === 0 }"></view>
            <text class="radio-label">男</text>
          </view>
          <view class="radio-item" @tap="gender = 1">
            <view class="radio-circle" :class="{ 'radio-active': gender === 1 }"></view>
            <text class="radio-label">女</text>
          </view>
          <view class="radio-item" @tap="gender = 2">
            <view class="radio-circle" :class="{ 'radio-active': gender === 2 }"></view>
            <text class="radio-label">保密</text>
          </view>
        </view>
      </view>
      
      <view class="button-group">
        <button class="cancel-btn" @tap="navigateBack">取消</button>
        <button class="save-btn" @tap="saveProfile">保存修改</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { userApi } from '../../api/user';
import storage from '../../utils/storage.js';

const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';
const avatarUrl = ref(defaultAvatarUrl);
const nickname = ref('');
const phone = ref('');
const email = ref('');
const gender = ref(0);

// 组件挂载时获取用户信息
onMounted(() => {
  getUserInfo();
});

// 获取用户信息
const getUserInfo = async () => {
  uni.showLoading({ title: '加载中...' });
  try {
    const res = await userApi.getUserInfo();
    if (res.code === 200 && res.data) {
      // 填充表单数据
      nickname.value = res.data.nickname || '';
      avatarUrl.value = res.data.avatar || '';
      phone.value = res.data.phone || '';
      email.value = res.data.email || '';
      gender.value = res.data.gender || 0;
    } else {
      uni.showToast({
        title: '获取用户信息失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取用户信息错误:', error);
    uni.showToast({
      title: '获取用户信息失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};



// 微信头像选择回调
const onChooseWxAvatar = (e) => {
  if (e.detail && e.detail.avatarUrl) {
    // 从微信获取的临时头像路径
    const tempFilePath = e.detail.avatarUrl;
    
    // 上传头像到服务器
    uploadAvatarImage(tempFilePath);
  }
};

// 上传头像图片到服务器
const uploadAvatarImage = (filePath) => {
  uni.showLoading({ title: '上传中...' });
  
  uni.uploadFile({
    url: 'http://localhost:1750/api/common/user/upload', // 直接使用服务器地址
    filePath: filePath,
    name: 'file',
    header: {
      'Authorization': storage.getToken() // 添加Authorization头
    },
    success: (uploadRes) => {
      // 解析返回结果
      try {
        const data = JSON.parse(uploadRes.data);
        if (data.code === 200) { // 使用正确的成功状态码
          // 上传成功，更新头像URL
          avatarUrl.value = data.data;
          uni.showToast({
            title: '头像上传成功',
            icon: 'success'
          });
        } else {
          uni.showToast({
            title: data.message || '上传失败', // 使用正确的消息字段
            icon: 'none'
          });
        }
      } catch (e) {
        console.error('解析上传结果失败:', e);
        uni.showToast({
          title: '上传失败，请重试',
          icon: 'none'
        });
      }
    },
    fail: () => {
      uni.showToast({
        title: '上传失败，请重试',
        icon: 'none'
      });
    },
    complete: () => {
      uni.hideLoading();
    }
  });
};

// 选择并上传图片
const chooseAndUploadImage = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      if (res.tempFilePaths && res.tempFilePaths.length > 0) {
        // 上传选择的图片
        uploadAvatarImage(res.tempFilePaths[0]);
      }
    }
  });
};

// 选择微信头像
const chooseWechatAvatar = () => {
  // 由于微信头像选择需要使用open-type="chooseAvatar"的button
  // 在非微信小程序环境下，使用普通的图片选择
  // #ifndef MP-WEIXIN
  chooseAndUploadImage();
  // #endif
  
  // #ifdef MP-WEIXIN
  // 在微信小程序环境下，提示用户直接点击头像
  uni.showToast({
    title: '请直接点击头像更换',
    icon: 'none',
    duration: 2000
  });
  // #endif
};

// 显示头像操作菜单
const showAvatarActionSheet = () => {
  uni.showActionSheet({
    itemList: ['使用微信头像', '从相册选择'],
    success: function (res) {
      if (res.tapIndex === 0) {
        // 使用微信头像
        chooseWechatAvatar();
      } else if (res.tapIndex === 1) {
        // 从相册选择并上传
        chooseAndUploadImage();
      }
    }
  });
};

// 微信昵称输入回调
const onNicknameBlur = (e) => {
  // 微信会自动安全检测，未通过会清空
  nickname.value = e.detail.value || nickname.value;
};

// 保存个人资料
const saveProfile = async () => {
  // 表单验证
  if (!nickname.value.trim()) {
    uni.showToast({ title: '昵称不能为空', icon: 'none' });
    return;
  }
  
  if (phone.value && !/^1[3-9]\d{9}$/.test(phone.value)) {
    uni.showToast({ title: '手机号格式不正确', icon: 'none' });
    return;
  }
  
  if (email.value && !/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(email.value)) {
    uni.showToast({ title: '邮箱格式不正确', icon: 'none' });
    return;
  }
  
  // 显示加载中
  uni.showLoading({ title: '保存中...' });
  
  try {
    const res = await userApi.updateUserInfo({
      nickname: nickname.value,
      avatar: avatarUrl.value,
      phone: phone.value || null,
      email: email.value || null,
      gender: gender.value
    });
    
    if (res.code === 200) {
      // 清除本地用户信息缓存，强制下次获取最新数据
      uni.removeStorageSync('userInfo');
      
      // 如果服务端返回了新的token，更新本地存储
      if (res.data && res.data.token) {
        storage.setToken(res.data.token);
        // 如果返回了用户信息，也更新本地用户信息
        if (res.data.user) {
          storage.setUserInfo(res.data.user);
        }
      }
      
      uni.showToast({ title: '保存成功', icon: 'success' });
      // 延迟返回，让用户看到成功提示
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      uni.showToast({ title: res.message || '保存失败', icon: 'none' });
    }
  } catch (e) {
    console.error('保存失败:', e);
    uni.showToast({ title: '保存失败，请重试', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
};
</script>

<style scoped>
.profile-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #e0e7ef 100%);
  display: flex;
  flex-direction: column;
}

/* 头部样式 */
.header {
  position: sticky;
  top: 0;
  display: flex;
  align-items: center;
  height: 90rpx;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  padding: 0 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-back {
  font-size: 40rpx;
  color: #333;
}

.header-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
  margin-right: 60rpx; /* 平衡左侧返回按钮 */
}

/* 头像部分样式 */
.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 0 40rpx 0;
}

/* 微信头像按钮样式 */
.avatar-btn {
  background: none;
  margin: 0;
  padding: 0;
  line-height: 1;
  border: none;
  outline: none;
}

.avatar-btn::after {
  border: none;
}

.avatar-container {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 20rpx;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-edit-icon {
  position: absolute;
  right: 10rpx;
  bottom: 10rpx;
  width: 60rpx;
  height: 60rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.icon-edit {
  font-size: 30rpx;
  color: #4f8cff;
}

.avatar-tip {
  color: #888;
  font-size: 26rpx;
  margin-top: 10rpx;
}

/* 表单部分样式 */
.form-section {
  flex: 1;
  background: #fff;
  border-radius: 30rpx 30rpx 0 0;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
  padding: 40rpx 30rpx;
  margin-top: 20rpx;
}

.form-item {
  margin-bottom: 36rpx;
}

.label {
  display: block;
  color: #333;
  font-size: 28rpx;
  font-weight: 500;
  margin-bottom: 12rpx;
}

.input {
  width: 100%;
  height: 90rpx;
  border: none;
  border-bottom: 1px solid #eee;
  font-size: 30rpx;
  padding: 0 10rpx;
  box-sizing: border-box;
  background: transparent;
  color: #333;
}

/* 单选按钮组样式 */
.radio-group {
  display: flex;
  align-items: center;
  margin-top: 10rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  margin-right: 40rpx;
}

.radio-circle {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 2rpx solid #ddd;
  margin-right: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.radio-active {
  border-color: #4f8cff;
  background: #4f8cff;
  position: relative;
}

.radio-active::after {
  content: '';
  width: 16rpx;
  height: 16rpx;
  background: #fff;
  border-radius: 50%;
  position: absolute;
}

.radio-label {
  font-size: 28rpx;
  color: #333;
}

/* 按钮组样式 */
.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 60rpx;
}

.cancel-btn {
  width: 46%;
  background: #f5f5f5;
  color: #666;
  border-radius: 12rpx;
  font-size: 32rpx;
  padding: 20rpx 0;
  text-align: center;
  border: none;
}

.save-btn {
  width: 46%;
  background: linear-gradient(90deg, #4f8cff 0%, #38c8ff 100%);
  color: #fff;
  border-radius: 12rpx;
  font-size: 32rpx;
  padding: 20rpx 0;
  text-align: center;
  box-shadow: 0 2rpx 8rpx rgba(79, 140, 255, 0.2);
  border: none;
}
</style> 